import { createRouter, createWebHistory } from 'vue-router'
import AuthPage from '../views/AuthPage.vue'
import RuleManagementPage from '../components/RuleManagementPage.vue'
import FeatureCards from '../views/FeatureCards.vue'
import ExcelPage from '../components/ExcelPage.vue'

const routes = [
  {
    path: '/',
    name: 'Login',
    component: AuthPage,
    meta: { requiresAuth: false }
  },
  {
    path: '/home',
    name: 'Home',
    component: FeatureCards,
    meta: { requiresAuth: true }
  },
  {
    path: '/rules',
    name: 'RuleManagement',
    component: RuleManagementPage,
    meta: { requiresAuth: true }
  },
  {
    path: '/records',
    name: 'Records',
    component: () => import('../components/PlaceholderPage.vue'),
    props: { title: '检验记录页面', message: '此页面正在开发中...' },
    meta: { requiresAuth: true }
  },
  {
    path: '/settings',
    name: 'Settings',
    component: () => import('../components/PlaceholderPage.vue'),
    props: { title: '设置页面', message: '此页面正在开发中...' },
    meta: { requiresAuth: true }
  },
  {
    path: '/excel',
    name: 'Excel',
    component: ExcelPage,
    meta: { requiresAuth: true }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/login'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

import { getCookie } from '../utils/cookieUtils'

// 添加路由守卫
router.beforeEach((to, _from, next) => {
  const token = getCookie('token')
  const isLoggedIn = token && localStorage.getItem('isLoggedIn') === 'true'
  
  if (to.meta.requiresAuth && !isLoggedIn) {
    next('/')
  } else if (to.path === '/' && isLoggedIn) {
    next('/home')
  } else {
    next()
  }
})

export default router